<template>
	<div class="select-main">
		<div class="tool-bar">
			<el-button @click="getTaskList">刷新</el-button>
			<el-button type="primary" @click="addSelectTask">新增</el-button>
			<el-button type="primary" @click="startAllTask">全部启动</el-button>
			<el-button type="danger" @click="stopAllTask">全部停止</el-button>
		</div>
		<div class="table-wrapper">
			<el-table :data="selectTaskList" style="width: 100%; height: 100%" border show-overflow-tooltip>
				<el-table-column type="index" width="50" align="center" fixed />
				<el-table-column prop="operate" label="操作" align="center" width="450" fixed>
					<template #default="scope">
						<el-button v-if="scope.row.status == 0" @click="editSelectTask(scope.row)">编辑</el-button>
						<el-button v-if="scope.row.status == 0" @click="copySelectTask(scope.row)">复制</el-button>
						<el-button v-if="scope.row.status == 0" type="primary" @click="startTask(scope.row.id)">启动</el-button>
						<el-button v-if="scope.row.status == 0" type="primary"
							@click="startTaskByGroupId(scope.row.groupId)">启动同组</el-button>
						<el-button v-if="scope.row.status == 1" type="danger" @click="stopTask(scope.row.id)">停止</el-button>
						<el-button v-if="scope.row.status == 1" type="primary"
							@click="stopTaskByGroupId(scope.row.groupId)">停止同组</el-button>
						<el-button v-if="scope.row.status == 0" type="danger" @click="deleteSelectTask(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="name" label="名称" width="180" align="center" fixed />
				<el-table-column prop="type" label="类型" width="120" align="center" fixed>
					<template #default="scope">
						<span v-if="scope.row.type == 1">实时数据</span>
						<span v-else>实时数据</span>
					</template>
				</el-table-column>
				<el-table-column prop="host" label="数据库地址" width="180" align="center" />
				<el-table-column prop="dbName" label="数据库" width="120" align="center" />
				<el-table-column prop="prefix" label="表前缀" width="120" align="center" />
				<el-table-column prop="startIndex" label="起始索引" width="120" align="center" />
				<el-table-column prop="tagNum" label="表格数量" width="180" align="center" />
				<el-table-column prop="status" label="状态" width="100" align="center">
					<template #default="scope">
						<el-tag v-if="scope.row.status == 0" type="danger">停止</el-tag>
						<el-tag v-else type="success">启动</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="startTime" label="开始时间" width="180" align="center">
					<template #default="scope">
						<span v-if="scope.row.startTime"> {{ scope.row.startTime }}</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column prop="endTime" label="结束时间" width="180" align="center">
					<template #default="scope">
						<span v-if="scope.row.endTime"> {{ scope.row.endTime }}</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column prop="timeInterval" label="时间间隔" width="100" align="center">
					<template #default="scope">
						<span>{{ scope.row.timeInterval + '分' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="groupId" label="分组ID" width="100" align="center" />
				<el-table-column prop="concurrentNum" label="并发数量" width="100" align="center" />
				<el-table-column prop="lastLog" label="最近一次日志" align="center" width="320">
					<template #default="scope">
						<span v-if="scope.row.lastLog"> {{ scope.row.lastLog }}</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column prop="lastTime" label="最近一次执行时间" align="center" width="180">
					<template #default="scope">
						<span v-if="scope.row.lastTime"> {{ scope.row.lastTime }}</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-dialog v-model="addOrEditDialogVisiable" :title="dialogTitle" width="550" :close-on-click-modal="false"
			destroy-on-close :close-on-press-escape="false">
			<el-form ref="ruleFormRef" style="max-width: 600px" :model="taskForm" label-width="auto" :rules="formRules">
				<el-form-item label="名称" prop="name">
					<el-input v-model.trim="taskForm.name" />
				</el-form-item>
				<el-form-item label="类型" prop="type">
					<el-select v-model="taskForm.type" placeholder="请选择">
						<el-option v-for="item in typeOption" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="数据库地址" prop="host">
					<div style="display: flex; width: 100%">
						<el-select v-model="taskForm.host" placeholder="请选择" @change="hostChange">
							<el-option v-for="item in localDatabaseOption" :key="item.value" :label="item.label"
								:value="item.value" />
						</el-select>
						<el-button style="margin-left: 6px">
							<el-icon @click="updateLocalDatabase">
								<Refresh />
							</el-icon>
						</el-button>
					</div>
				</el-form-item>
				<el-form-item label="数据库" prop="dbName">
					<el-select v-model="taskForm.dbName" placeholder="请选择">
						<el-option v-for="item in databaseOption" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="表前缀" prop="prefix">
					<el-input v-model.trim="taskForm.prefix" />
				</el-form-item>
				<el-form-item label="起始索引" prop="startIndex">
					<el-input-number v-model="taskForm.startIndex" :min="0" :precision="0" :step="1" style="width: 100%" />
				</el-form-item>
				<el-form-item label="表格数量" prop="tagNum">
					<el-input-number v-model="taskForm.tagNum" :min="0" :precision="0" :step="1" style="width: 100%" />
				</el-form-item>
				<el-form-item v-if="taskForm.type == 2" label="开始时间" prop="startTime">
					<el-date-picker v-model="taskForm.startTime" type="datetime" placeholder="开始时间" style="width: 100%" />
				</el-form-item>
				<el-form-item v-if="taskForm.type == 2" label="结束时间" prop="endTime">
					<el-date-picker v-model="taskForm.endTime" type="datetime" placeholder="结束时间" style="width: 100%" />
				</el-form-item>
				<el-form-item v-if="taskForm.type == 2" label="时间间隔(分)" prop="timeInterval">
					<el-input-number v-model="taskForm.timeInterval" :min="0" :precision="0" :step="1" style="width: 100%" />
				</el-form-item>
				<el-form-item label="分组ID" prop="groupId">
					<el-input-number v-model="taskForm.groupId" :min="0" :precision="0" :step="1" style="width: 100%" />
				</el-form-item>
				<el-form-item label="并发数量" prop="concurrentNum">
					<el-input-number v-model="taskForm.concurrentNum" :min="1" :precision="0" :step="1" style="width: 100%" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="addOrEditDialogVisiable = false">取消</el-button>
					<el-button type="primary" @click="saveSelectTask"> 确认 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="js" setup>
import { onMounted, ref, defineProps } from 'vue';
//store
const props = defineProps({
	dbInfo:{
		type:Object,
		default:{}
	},
	databaseInfo:{
		type:Array,
		default:[]
	}
})
import { showDatabases } from '@/api/index'
const store = {
	info:props.dbInfo,
	databaseInfo:props.databaseInfo
}
//表格相关
import { list, saveOrUpdate, deleteById, start, startAll, startByGroupId, stop, stopAll, stopByGroupId } from '../../api/select';
import { ElMessage, ElMessageBox } from 'element-plus';
const selectTaskList = ref([]);
const getTaskList = () => {
	let data = {
		curHost: store.info.host
	}
	list(data).then(res => {
		if (res.code == 200 && res.data) {
			selectTaskList.value = res.data;
		} else {
			selectTaskList.value.length = 0;
		}
	}).catch(e => {
		console.log(e);
	})
}
//从本地存储里面获取数据库信息
const localDatabase = ref([]);
const localDatabaseOption = ref([])
const updateLocalDatabase = () => {
	let dataStr = window.localStorage.getItem("allDbsInfo");
	if (!dataStr) {
		return;
	}
	let data = JSON.parse(dataStr);
	localDatabase.value = JSON.parse(JSON.stringify(data));
	let temp = Array.from(new Set(data.map(item => {
		return item.host;
	})))
	localDatabaseOption.value = temp.map(item => {
		return {
			value: item,
			label: item
		}
	})
}
onMounted(() => {
	getTaskList();
	updateLocalDatabase();
})

const addOrEditDialogVisiable = ref(false);
const dialogTitle = ref("新增");
const template = {
	id: "",
	name: "",
	type: "1",
	startIndex: 0,
	tagNum: 1,
	prefix: '',
	startTime: '',
	endTime: '',
	host: '',
	port: 6041,
	user: 'root',
	password: 'tasodata',
	dbName: '',
	concurrentNum: 1,
	timeInterval: 1,
	groupId: 1,
	curHost: '',
	lastTime: '',
	lastLog: ''
}
const taskForm = ref(JSON.parse(JSON.stringify(template)));
const typeOption = [
	{ value: "1", label: "实时数据" },
	{ value: "2", label: "历史数据" },
]
//编辑
const editSelectTask = (row) => {
	taskForm.value = JSON.parse(JSON.stringify(row));
	taskForm.value.type = taskForm.value.type + ''
	updateDatabase();
	addOrEditDialogVisiable.value = true;
}

//复制
const copySelectTask = (row) => {
	taskForm.value = JSON.parse(JSON.stringify(row));
	taskForm.value.type = taskForm.value.type + ''
	updateDatabase();
	taskForm.value.id = ""
	taskForm.value.lastLog = ''
	taskForm.value.lastTime = ''
	addOrEditDialogVisiable.value = true;
}

//删除
const deleteSelectTask = (id) => {
	ElMessageBox.confirm("确认要删除该任务吗？", "提示").then(() => {
		deleteById({ id }).then(res => {
			if (res.code == 200 && res.data) {
				getTaskList();
				ElMessage.success("删除成功")
			} else {
				ElMessage.error("删除失败：" + res.msg);
			}
		}).catch(e => {
			console.error(e);
			ElMessage.error("删除失败");
		})
	})
}

//新增
const addSelectTask = () => {
	taskForm.value = JSON.parse(JSON.stringify(template));
	addOrEditDialogVisiable.value = true;
}

const hostChange = (val) => {
	let target = localDatabase.value.filter(item => item.host == val)[0];
	if (!target) {
		return;
	}
	taskForm.value.port = Number(target.port);
	taskForm.value.user = target.username;
	taskForm.value.password = target.password;
	taskForm.value.dbName = "";
	updateDatabase();
}

const databaseOption = ref([]);
const updateDatabase = () => {
	let { host, port, user, password } = taskForm.value;
	let data = {
		host,
		port,
		password,
		username: user,
	}
	showDatabases(data).then(res => {
		if (res.code == 200 && res.data) {
			databaseOption.value = res.data.map(item => {
				return {
					value: item,
					label: item
				}
			})
		} else {
			databaseOption.value.length = 0;
		}
	}).catch(error => {
		console.error(error);
	})
}

const concurrentNumCheck = (rules, value, callback) => {
	if (!value) {
		callback(new Error("请输入并发数量"))
	} else {
		callback();
	}
}
const groupIdCheck = (rules, value, callback) => {
	if (!value) {
		callback(new Error("请输入分组ID"))
	} else {
		callback();
	}
}
const tagNumCheck = (rules, value, callback) => {
	if (!value) {
		callback(new Error("请输入表格数量"))
	} else {
		callback();
	}
}
const startIndexCheck = (rules, value, callback) => {
	if (!value && value !== 0) {
		callback(new Error("请输入起始索引"))
	} else {
		callback();
	}
}

const timeIntervalCheck = (rules, value, callback) => {
	if (!value && value !== 0) {
		callback(new Error("请输入时间间隔"))
	} else {
		callback();
	}
}

const nameCheck = (rules, value, callback) => {
	let data = selectTaskList.value;
	let sameNameTask = data.filter(item => item.name == value && taskForm.value.id != item.id);
	if (sameNameTask.length > 0) {
		callback(new Error("名称重复"))
	} else {
		callback();
	}
}

const startTimeCheck = (rules, value, callback) => {
	if (!value) {
		callback(new Error("请输入开始时间"))
	} else {
		callback()
	}
}

const endTimeCheck = (rules, value, callback) => {
	if (!value) {
		callback(new Error("请输入结束时间"))
	} else {
		callback()
	}
}
const formRules = ref({
	name: [
		{ required: true, message: '请输入任务名称', trriger: 'blur' },
		{ required: true, validator: nameCheck, trriger: 'blur' },
	],
	type: [
		{ required: true, message: '请选择任务类型', trriger: ['change', 'blur'] }
	],
	host: [
		{ required: true, message: '请选择数据库地址', trriger: ['change', 'blur'] }
	],
	dbName: [
		{ required: true, message: '请选择数据库', trriger: ['change', 'blur'] }
	],
	prefix: [
		{ required: true, message: '请输入表前缀', trriger: 'blur' }
	],
	startIndex: [
		{ required: true, validator: startIndexCheck, trriger: 'blur' }
	],
	tagNum: [
		{ required: true, validator: tagNumCheck, trriger: 'blur' }
	],
	groupId: [
		{ required: true, validator: groupIdCheck, trriger: 'blur' }
	],
	concurrentNum: [
		{ required: true, validator: concurrentNumCheck, trriger: 'blur' }
	],
	startTime: [
		{ required: true, validator: startTimeCheck, trriger: ['change', 'blur'] }
	],
	endTime: [
		{ required: true, validator: endTimeCheck, trriger: ['change', 'blur'] }
	],
	timeInterval: [
		{ required: true, validator: timeIntervalCheck, trriger: 'blur' }
	],
})


const ruleFormRef = ref(null);
const saveSelectTask = () => {
	ruleFormRef.value.validate((valid) => {
		if (valid) {
			let data = JSON.parse(JSON.stringify(taskForm.value));
			//当前数据库的HOST
			data.curHost = store.info.host;
			saveOrUpdate(data).then(res => {
				if (res.code == 200 && res.data) {
					getTaskList();
					ElMessage.success("保存成功")
				} else {
					ElMessage.error(res.msg);
				}
				addOrEditDialogVisiable.value = false;
			}).catch(e => {
				ElMessage.error(e);
				addOrEditDialogVisiable.value = false;
			})
		}
	})
}

const startTask = (id) => {
	start({ id }).then(res => {
		if (res.code == 200 && res.data) {
			ElMessage.success("启动成功")
			getTaskList();
		} else {
			ElMessage.error("启动失败")
		}
	})
}

const startTaskByGroupId = (groupId) => {
	startByGroupId({ groupId }).then(res => {
		if (res.code == 200 && res.data) {
			ElMessage.success("启动成功")
			getTaskList();
		} else {
			ElMessage.error("启动失败")
		}
	})
}

const startAllTask = () => {
	startAll().then(res => {
		if (res.code == 200 && res.data) {
			ElMessage.success("启动成功")
			setTimeout(()=>{
				getTaskList();
			},1000);
		} else {
			ElMessage.error("启动失败")
		}
	})
}


const stopTask = (id)=>{
	stop({id}).then(res => {
		if (res.code == 200 && res.data) {
			ElMessage.success("停止成功")
			getTaskList();
		} else {
			ElMessage.error("停止失败")
		}
	})
}

const stopTaskByGroupId = (groupId)=>{
	stopByGroupId({groupId}).then(res => {
		if (res.code == 200 && res.data) {
			ElMessage.success("停止成功")
			getTaskList();
		} else {
			ElMessage.error("停止失败")
		}
	})
}

const stopAllTask = ()=>{
	stopAll().then(res => {
		if (res.code == 200 && res.data) {
			ElMessage.success("停止成功")
			setTimeout(()=>{
				getTaskList();
			},1000);
		} else {
			ElMessage.error("停止失败")
		}
	})
}

</script>
<style lang="less" scoped>
.select-main {
	width: 100%;
	height: 100%;
	overflow: auto;
	padding: 16px;

	.tool-bar {
		height: 32px;
		display: flex;
		align-items: center;
	}

	.table-wrapper {
		height: calc(100% - 50px);
		margin-top: 16px;
	}
}
</style>
